<template>
  <div class="wrapper-form">
    <el-form
      ref="form"
      :model="formData"
      @submit.prevent.capture="onSubmit(form)"
      :rules="rules"
      label-position="left"
      label-width="80"
    >
      <el-form-item prop="name" label="名称" required>
        <el-input name="name" v-model="formData.name" placeholder="输入" />
      </el-form-item>
      <el-form-item prop="dataType" label="权限类型" required>
        <el-select v-model="formData.dataType" placeholder="选择" size="default">
          <el-option
            v-for="item in dataTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-tooltip content="具体权限可以稍后在 [权限编辑] 中更改" placement="top">
          <el-icon style="margin-left: 15px"><InfoFilled /></el-icon>
        </el-tooltip>
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button @click="onCancel" text>取消</el-button>
      <el-button type="primary" @click="onSubmit(form)"> 确认 </el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onBeforeMount } from "vue";
import type { FormInstance, FormRules } from "element-plus";

import { fetchRoleAdd } from "@/http/role";
import type { RoleAddType } from "@vs/Role/RoleType";

const emit = defineEmits<{
  (e: "close", refresh: boolean): void;
}>();
defineProps(["dataTypeList"]);

const form = ref<FormInstance>();
const formData = reactive<RoleAddType>({
  dataType: "ME_DATA",
  name: "",
  functions: []
});

const onSubmit = function (event: FormInstance) {
  if (!event) return;
  event.validate((result: boolean) => {
    if (!result) return;
    fetchRoleAdd(formData)
      .then(() => {
        emit("close", true);
      })
      .finally(resetField);
  });
};
const resetField = function () {
  form.value?.resetFields();
};
onBeforeMount(() => {});

const rules = reactive<FormRules>({
  dataType: [{ required: true, message: "此项必填" }],
  name: [{ required: true, message: "此项必填" }]
});

const onCancel = function () {
  emit("close", false);
  resetField();
};
</script>

<style scoped>
.wrapper-form {
  height: 160px;
  overflow-y: auto;
}
.dialog-footer {
  position: absolute;
  bottom: 30px;
  right: 30px;
}
</style>
